package com.example.test.chapter8.timepicker;

import java.util.Calendar;

import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

import com.example.test.R;
import com.example.test.chapter8.MainChapter8;

public class MyTimePicker extends Activity {
	private TextView mTimeDisplay;
	private Button mPichTime;
	private int mHour;
	private int mMinute;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.timepicker);
		mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
		mPichTime = (Button) findViewById(R.id.pickTime);
		mPichTime.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialog(0);
			}
		});
		Calendar calendar = Calendar.getInstance();
		mHour = calendar.get(Calendar.HOUR_OF_DAY);
		mMinute = calendar.get(Calendar.MINUTE);
		updateTime();
		Button btn = (Button) findViewById(R.id.backpage);
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(),
						MainChapter8.class);
				startActivity(intent);
				finish();
			}
		});
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 0:
			return new TimePickerDialog(this, listener, mHour, mMinute, true);
		}
		return null;
	}

	public void updateTime() {
		mTimeDisplay.setText(new StringBuffer().append(onPad(mHour))
				.append(" : ").append(onPad(mMinute)));
	}

	private TimePickerDialog.OnTimeSetListener listener = new OnTimeSetListener() {

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			mHour = hourOfDay;
			mMinute = minute;
			updateTime();
		}
	};

	private String onPad(int number) {
		if (number < 10) {
			return "0" + number;
		}
		return String.valueOf(number);
	}
}
